package com.jf.cloud.service.sysmanager.common.util;

import org.apache.commons.logging.Log;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * TODO  验证帮助类
 * @author ouyang 创建时间：2012-06-02 14:38:19
 */
public class ValidateUtil {
    static Validator validator=null;
    static{ //初始化验证环境
    	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	    validator = factory.getValidator();  
    }
    /**
     * TODO 获取验证器  
     */
    public static Validator get() {
		return validator;
	}
    /**
     * 验证一个类全部的 注解属性 得到真假 结果
     */
    public static <T> boolean validateAllPropety(T t) {
    	Set<ConstraintViolation<T>> msg = get().validate(t);
		return msg.size()<=0;
	}
    /**
     * 验证一个类全部的 注解属性 得到List<String> 结果说明信息
     */
    public static <T> List<String> validateAll(T t) {
    	Set<ConstraintViolation<T>> msg = get().validate(t);
    	List<String> rs = new ArrayList<String>();
    	for (ConstraintViolation<T> cv : msg) {
    		rs.add(cv.getPropertyPath()+"属性:"+cv.getMessage());
		}
    	return rs;
    }
    /**
     * 验证一个类全部的 一个属性
     * 返回值：成功 ""
     *        失败 则为错误信息
     */
    public static <T> String validatePropety(T t, String fileName) {
    	Set<ConstraintViolation<T>> msg = get().validateProperty(t,fileName);
    	List<String> rs = new ArrayList<String>();
    	for (ConstraintViolation<T> cv : msg) {
    		rs.add(cv.getPropertyPath()+"属性:"+cv.getMessage());
		}
    	return rs.size()>0?rs.get(0):"";
    }
    /**
     * 打印错误信息
     * TODO  
     */
    public static void ShowMessage(List<String> rs, Log log){
    	StringBuffer sf = new StringBuffer(100);
    	for (String er : rs) {
    		sf.append(" |  "+er);
		}
    	log.error("参数验证失败错误原因如下:"+sf.toString());
    }
    
}
